<template>
  <div class="question-category">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="page-title">
        <h1>题目分类管理</h1>
        <p class="text-muted">管理面试题目的分类和标签</p>
      </div>
      <div class="page-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>添加分类
        </el-button>
      </div>
    </div>

    <!-- 分类列表 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">分类列表</span>
        </div>
      </template>

      <el-table
          v-loading="loading"
          :data="tableData"
          :empty-text="'暂无数据'"
          element-loading-background="rgba(255, 255, 255, 0.8)"
          element-loading-spinner="el-icon-loading"
          element-loading-text="加载中..."
          style="width: 100%"
      >
        <el-table-column label="ID" prop="id" width="60" align="center">
          <template #default="scope">
            <span>{{ scope?.row?.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="分类名称" prop="name" align="center">
          <template #default="scope">
            <span>{{ scope?.row?.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="描述" prop="description" align="center">
          <template #default="scope">
            <span>{{ scope?.row?.description }}</span>
          </template>
        </el-table-column>
        <el-table-column label="题目数量" prop="questionCount" align="center">
          <template #default="scope">
            <span>{{ scope?.row?.questionCount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createdAt" align="center">
          <template #default="scope">
            <span>{{ formatDateTime(scope?.row?.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope?.row?.status === 0 ? 'success' : 'warning'">
              {{ scope?.row?.status === 0 ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="scope">
            <div class="operation-buttons" v-if="scope?.row">
              <el-link type="primary" :underline="false" @click="handleEdit(scope.row)">
                <el-icon><Edit /></el-icon>编辑
              </el-link>
              <el-link type="danger" :underline="false" @click="handleDelete(scope.row)">
                <el-icon><Delete /></el-icon>删除
              </el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :background="true"
            :page-sizes="[5, 10, 20, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑分类对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '添加题目分类' : '编辑题目分类'"
        width="500px"
    >
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类描述" prop="description">
          <el-input
              v-model="form.description"
              :rows="3"
              placeholder="请输入分类描述"
              type="textarea"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">启用</el-radio>
            <el-radio :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { getQuestionCategoryList, addQuestionCategory, updateQuestionCategory, deleteQuestionCategory, getCountQuestionsByCategory } from '@/api/questionCategory'

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  if (isNaN(date.getTime())) return ''

  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')

  return `${year}-${month}-${day}`
}

// 表格数据
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = reactive({
  id: '',
  name: '',
  description: '',
  status: 0
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取分类列表
const getList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }
    const res = await getQuestionCategoryList(params)
    if (res?.data?.records) {
      // 获取每个分类的题目数量
      const categories = res.data.records
      for (const category of categories) {
        try {
          const countRes = await getCountQuestionsByCategory({ name: category.name })
          // 由于后端直接返回数字，不需要检查 code
          category.questionCount = typeof countRes === 'number' ? countRes : 0
        } catch (error) {
          category.questionCount = 0
        }
      }
      tableData.value = categories
      total.value = res.data.total || 0
    } else {
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 添加分类
const handleAdd = () => {
  dialogType.value = 'add'
  form.id = ''
  form.name = ''
  form.description = ''
  form.status = 0
  dialogVisible.value = true
}

// 编辑分类
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 删除分类
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '确定要删除该分类吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      await deleteQuestionCategory(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除分类失败:', error)
      ElMessage.error('删除分类失败')
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await addQuestionCategory(form)
          ElMessage.success('添加成功')
        } else {
          await updateQuestionCategory(form)
          ElMessage.success('修改成功')
        }
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error('保存分类失败:', error)
        ElMessage.error('保存分类失败')
      }
    }
  })
}

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getList()
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
:root {
  --primary-color: #3498db;
  --primary-light: #5dade2;
  --primary-dark: #2980b9;
  --secondary-color: #2ecc71;
  --accent-color: #e67e22;
  --success-color: #27ae60;
  --warning-color: #f39c12;
  --danger-color: #e74c3c;
  --info-color: #17a2b8;
  --gray-100: #f8f9fa;
  --gray-200: #e9ecef;
  --gray-300: #dee2e6;
  --gray-400: #ced4da;
  --gray-500: #adb5bd;
  --gray-600: #6c757d;
  --gray-700: #495057;
  --gray-800: #343a40;
  --gray-900: #212529;
  --body-bg: #f5f5f5;
  --card-bg: #ffffff;
  --card-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  --border-radius: 4px;
  --spacing-xs: 4px;
  --spacing-sm: 8px;
  --spacing-md: 16px;
  --spacing-lg: 24px;
  --spacing-xl: 32px;
}

.question-category {
  padding: var(--spacing-lg);
  background-color: var(--body-bg);
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: var(--spacing-lg);
}

.page-title h1 {
  font-size: 24px;
  font-weight: 500;
  margin-bottom: var(--spacing-xs);
  color: var(--gray-800);
}

.page-title p {
  color: var(--gray-600);
  font-size: 14px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-md) var(--spacing-lg);
  border-bottom: 1px solid var(--gray-200);
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  color: var(--gray-800);
}

.pagination-container {
  margin-top: var(--spacing-lg);
  display: flex;
  justify-content: flex-end;
  padding: var(--spacing-md) var(--spacing-lg);
  border-top: 1px solid var(--gray-200);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: var(--spacing-md);
}

:deep(.el-card) {
  border-radius: var(--border-radius);
  box-shadow: var(--card-shadow);
  border: none;
}

:deep(.el-table) {
  --el-table-border-color: var(--gray-200);
  --el-table-header-bg-color: var(--gray-100);
  --el-table-row-hover-bg-color: var(--gray-100);
}

:deep(.el-tag) {
  border-radius: var(--border-radius);
}

:deep(.el-button-group) {
  display: flex;
  gap: var(--spacing-xs);
}

:deep(.el-button) {
  border-radius: var(--border-radius);
}

:deep(.el-dialog) {
  border-radius: var(--border-radius);
}

:deep(.el-dialog__header) {
  padding: var(--spacing-md) var(--spacing-lg);
  border-bottom: 1px solid var(--gray-200);
  margin: 0;
}

:deep(.el-dialog__body) {
  padding: var(--spacing-lg);
}

:deep(.el-dialog__footer) {
  padding: var(--spacing-md) var(--spacing-lg);
  border-top: 1px solid var(--gray-200);
}

.operation-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 12px;
}

.operation-buttons .el-link {
  display: flex;
  align-items: center;
  gap: 4px;
}

.operation-buttons .el-icon {
  font-size: 16px;
}
</style> 